import router from './routers'
import { goRouter } from '../libs/com'
import { setSession, getSession } from '../libs/cache'
import { getLocalStorage } from '../api/android'
import { userRouter, comRouter, cgxsRouter, tsxsRouter, xljxRouter, bdzsRouter, shenheRouter, errorRouter } from './getRouter'

var getRouters
// 合并当前所有的路由
const newRouters = (to, next) => {
	const routerArr = userRouter.concat(comRouter).concat(getRouters).concat(errorRouter)
    router.addRoutes(routerArr)
    global.antRouter = routerArr
    next({ ...to, replace: true })
}
// 当前路由的标题
const routersTitle = title => {
	title = title || '输电线路数字化APP';
    window.document.title = title
}



router.beforeEach((to, from, next) => {
	goRouter(to, from)
	if(!getRouters){
        getRouters = cgxsRouter.concat(tsxsRouter).concat(xljxRouter).concat(bdzsRouter).concat(shenheRouter)
        newRouters(to, next)
	}
    if(!getSession("token") && to.path !== '/login'){
		routersTitle(to.meta.title)
		next({
            path: '/login'
        })
		return
	}else if(getSession("token") && to.path === '/login'){
		routersTitle(to.meta.title)
		next({
            path: '/index'
        })
		return
	}else{
		routersTitle(to.meta.title)
		if(to.path === ''){
	        next({
                path: '/'
            })
	        return
	    }else if(to.path === 'login'){
	    	next({
                path: 'index'
            })
	        return
	    }else{
	        next()
	        return
	    }
	}
})

router.afterEach((to, from) => {
    window.scrollTo(0, 0)
})
export default router
